package com.kly.cashmall.module.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;

import androidx.annotation.Nullable;

import com.kly.cashmall.R;
import com.kly.cashmall.bean.UpdateBean;
import com.kly.cashmall.event.HomePageEvent;
import com.kly.cashmall.event.LoginEvent;
import com.kly.cashmall.framework.module.BaseActivity;
import com.kly.cashmall.framework.mvp.PresenterLifeCycle;
import com.kly.cashmall.module.home.home_tab.FragmentClassMap;
import com.kly.cashmall.module.home.home_tab.tab_container.HomePagesManager;
import com.kly.cashmall.module.home.home_tab.tab_container.TabController;
import com.kly.cashmall.module.home.home_tab.tab_other.HomeTabObserver;
import com.kly.cashmall.module.home.home_tab.tab_other.ObsRunnable;
import com.kly.cashmall.module.home.home_tab.tab_view.FragmentPackage;
import com.kly.cashmall.module.home.home_tab.tab_view.HomeMainMenuAction;
import com.kly.cashmall.module.home.home_tab.tab_view.MenuTabInfo;
import com.kly.cashmall.module.home.presenter.HomePagePresenter;
import com.kly.cashmall.module.home.presenter.HomePageViewer;
import com.kly.cashmall.module.login.LoginActivity;
import com.kly.cashmall.module.web.WebViewActivity;
import com.kly.cashmall.popup.UpdatePopupWindow;
import com.kly.cashmall.services.UserInfoHelper;
import com.kly.cashmall.utils.function.BundleHelper;
import com.kly.cashmall.utils.function.PressHandle;
import com.kly.cashmall.utils.data.TextUtil;
import com.kly.cashmall.utils.function.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author
 * @buildBy plugin
 */
public class HomePageActivity extends BaseActivity implements HomePageViewer{

    public static final String HOME_POSITION = "HOME_POSITION";
    private static final String TAG = HomePageActivity.class.getSimpleName();

    @PresenterLifeCycle
    HomePagePresenter presenter = new HomePagePresenter(this);

    private TabController mTabController;
    private HomePagesManager mHomePagesManager;

    private String mStorePosTag;
    private static final int NEED_LOGIN_CODE = 0x333;
    private int currentPos;
    private UpdatePopupWindow updatePopupWindow;

    /**
     * 黑字透明状态栏
     */
    @Override
    protected boolean darkMode() {
        return true;
    }


    /**
     * 跳转到指定的TAB
     */
    public static Intent newIntent(Context context, String tag, Bundle bundle) {
        Intent intent = new Intent(context, HomePageActivity.class);
        intent.putExtra(HOME_POSITION, tag);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        return intent;
    }

    @Override
    protected void setView(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_home_page);
        EventBus.getDefault().register(this);
        mTabController = new TabController(this, findViewById(R.id.home_page_tab_container));
        mTabController.setOnItemClickListener((pos, view) -> {
            currentPos = pos;
            if (!UserInfoHelper.getInstance().isLogin() && mTabController.getTabItem(pos).judgeNeedLogin() == 1) {
                startActivityForResult(LoginActivity.callIntent(this), NEED_LOGIN_CODE);
                return false;
            }
            showFragment(currentPos, null);
            return true;
        });
        mHomePagesManager = new HomePagesManager();
        mStorePosTag = savedInstanceState == null ? "" : savedInstanceState.getString(HOME_POSITION);
        HomeTabObserver.newInstance().registerObserve(hashCode(), new ObsRunnable<String>() {
            @Override
            public void run(String tag) {
                showFragmentByTag(tag, null);
            }
        });
        
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            mStorePosTag = intent.getStringExtra(HOME_POSITION);
            if (!TextUtil.isEmpty(mStorePosTag)) {
                showFragmentByTag(mStorePosTag, intent.getExtras());
            }
        }
    }

    @Override
    protected void loadData() {
        presenter.preLoad();
        presenter.getAppCode();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 交由tabController控制tab切换和传参
     */
    private void showFragment(int pos, Bundle bundle) {
        if (pos >= 0 && mTabController != null) {
            mTabController.setSelection(pos, bundle);
        }
    }


    /**
     * 根据TAG标签显示Fragment
     */
    public void showFragmentByTag(String tag, Bundle bundle) {
        if (mTabController != null) {
            mTabController.setSelectionByTag(tag, bundle);
        }
    }

    /**
     * 查看首页有没有相应tab，有就跳转
     */
    public boolean findAndJumpByTag(String tag, Bundle bundle) {
        if (mTabController != null) {
            if (mTabController.findIndexByTag(tag) >= 0) {
                mTabController.setSelectionByTag(tag, bundle);
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(BundleHelper.create(outState)
                .putString(HOME_POSITION, mTabController.getCurrentTag())
                .get());
    }

    /**
     * 双击退出
     */
    private PressHandle pressHandle;

    @Override
    public boolean interceptBack() {
        if (pressHandle == null) {
            pressHandle = new PressHandle(this);
        }
        return super.interceptBack() || pressHandle.handlePress(KeyEvent.KEYCODE_BACK);
    }

    @Override
    protected void willDestroy() {
        super.willDestroy();
        mHomePagesManager.clear();
    }

    @Override
    public void onGetMenuListSuccess(List<HomeMainMenuAction> menuActionList) {
        setMenuList(menuActionList);
    }

    @Override
    public void getAppCodeSuccess(UpdateBean appCodeBean) {
        showUpdateDialog(appCodeBean);
    }

    @Override
    public void getAppCodeFailed() {

    }

    private void setMenuList(List<HomeMainMenuAction> infoList) {
        List<FragmentPackage<MenuTabInfo>> fragmentPackageList = new ArrayList<>();

        for (int i = 0; infoList != null && i < infoList.size(); i++) {
            FragmentPackage<MenuTabInfo> fragmentPackage =
                    FragmentClassMap.buildFragmentPackage(MenuTabInfo.buildHomeMainMenuAction(infoList.get(i)));
            if (fragmentPackage != null) {
                fragmentPackageList.add(fragmentPackage);
            }

        }

        if (fragmentPackageList.isEmpty()) {
            fragmentPackageList = FragmentClassMap.findDefaultFragments();
        }

        mTabController.clearAllTab();
        mHomePagesManager.setFragmentPackages(this, fragmentPackageList);
        mTabController.addTabs(mHomePagesManager.getTabItems());
        showFragmentByTag(mStorePosTag, null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == NEED_LOGIN_CODE && resultCode == Activity.RESULT_OK) {
            showFragment(currentPos, null);
        }
    }

    private void showUpdateDialog(final UpdateBean appCodeBean) {
        if (!appCodeBean.isNeedUpdate()) {
            return;
        }

        String forceUpdateDesc = appCodeBean.getForceUpdateDesc();
        if (TextUtil.isEmpty(forceUpdateDesc)) {
            forceUpdateDesc = getResources().getString(R.string.update_tip);
        }
        boolean forceUpdate = appCodeBean.isForceUpdate();
        updatePopupWindow = new UpdatePopupWindow(this, getResources().getString(R.string.update_title), forceUpdateDesc,
                new UpdatePopupWindow.Callback() {
                    @Override
                    public void onCallBack(UpdatePopupWindow generalOneDialog) {
                        openAppsMarket(appCodeBean.getReviewUrl());

                    }
                });
        updatePopupWindow.setPopupGravity(Gravity.CENTER);
        updatePopupWindow.showPopupWindow();
        updatePopupWindow.setCloseButton(forceUpdate);
        updatePopupWindow.setIcon(R.mipmap.ic_upgrade);
        updatePopupWindow.setTextGravity(appCodeBean.getForceUpdateDescLayout() == 1 ? Gravity.CENTER_HORIZONTAL : appCodeBean.getForceUpdateDescLayout() == 2 ? Gravity.LEFT : Gravity.RIGHT);
        updatePopupWindow.setBtnText(getString(R.string.all_confirm));

    }

    private void openAppsMarket(String url) {
        //goto google play detail page
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + getApplication().getPackageName()));
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + getApplication().getPackageName()));
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                ToastUtil.showToast("Please visit " + url);
                startActivity(WebViewActivity.callIntent(this, "", url));
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEvent(HomePageEvent mainEvent) {
        presenter.preLoad();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReLogin(LoginEvent event) {
        startActivity(LoginActivity.callIntent(getActivity()));
        finish();
    }
}
